<template>
    <div class="app-container">
        <el-row>
            <el-col>
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                    label-width="88px">
                    <el-col>
                        <!-- <el-form-item label="状态" prop="radio">
               <el-radio-group v-model="radio">
                 <el-radio v-model="radio" :label="1" :disabled="disabled">禁用</el-radio>
                 <el-radio v-model="radio" :label="2" :disabled="disabled">使用</el-radio>
               </el-radio-group>
             </el-form-item> -->
                        <!-- <el-form-item label="类型" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择类型" clearable @keyup.enter.native="handleQuery">
                <el-option label="请选择类型" :value="0" />
                <el-option label="年终结算审核" :value="-1" />
                <el-option label="院级经费使用审核" :value="2" />
                <el-option label="岗位变动审核" :value="3" />
                <el-option label="选岗审核" :value="1" />
                <el-option label="特殊工作量审核" :value="-2" />
              </el-select>
            </el-form-item> -->
                    </el-col>
                    <el-form-item label="关键字" prop="keyword">
                        <el-input v-model="queryParams.keyword" placeholder="" clearable
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    

                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                            @click="handleDelete" v-hasPermi="['datasourceBase:remove']">删除</el-button>
                    </el-col>

                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>


                <el-table v-loading="loading" :data="logList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="序号" align="center" type="index" width="0" />
                    <el-table-column label="日期" align="center" prop="data" width="100" />
                    <el-table-column label="标题" align="center" prop="title" width="200" />
                    <el-table-column label="内容" align="center" prop="content" width="200" />
                    <el-table-column label="通知用户" align="center" prop="inform" width="200" />
                    <el-table-column label="状态" align="center" prop="status">
                        <template slot-scope="scope">
                            <span style="color:#ffba00" v-if="scope.row.status == 0">正常</span>
                            <span style="color:#1890ff" v-else-if="scope.row.status == 1">审核中</span>
                            <span style="color:rgb(26, 179, 148)" v-else-if="scope.row.status == 2">成功</span>
                            <span style="color:red" v-else-if="scope.row.status == 3">失败</span>
                            <span v-else>正常</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit"  @click="handleAdd"
                                v-hasPermi="['account:edit']">详情</el-button>
                            
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['account:remove']">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="baseTotal > 0" :total="baseTotal" :page.sync="queryParams.currPage"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
                <!--         添加或修改数据通道信息对话框-->
                <el-dialog :title="UpdateTitle" :visible.sync="UpdateOpen" width="700px" append-to-body>

                    <!--          人工注册表单-->
                    <el-form ref="baseAddForm" :model="baseAddForm" label-width="150px" v-if="radio === 1"
                        :rules="baseAddRules">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="标题" prop="resourceName" required>
                                    <el-input v-model="baseAddForm.resourceName" placeholder="" />
                                </el-form-item>
                            </el-col>


                            <el-form>
                            </el-form>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="内容" prop="unit" required>
                                    <el-input v-model="baseAddForm.unit" placeholder="" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        
                        <el-form-item label="通知用户" required  v-if="jieshoushow">
                  <el-select v-model="dataBaseType" multiple placeholder="">
                    <el-option
                      v-for="item in dataBaseTypeList"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel">
                    </el-option>
                  </el-select>
                  

                </el-form-item>
                       

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
                
                <!--         查看详情对话框-->
                <el-dialog :title="DetailTitle" :visible.sync="DetailOpen" width="1200px" append-to-body>
                    <el-form ref="form" :model="baseDetailForm">
                        <el-form label-width="100px" :rules="rules" :model='baseDetailForm'>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="名称" prop="dataBaseName">
                                        <el-input v-model="baseDetailForm.resourceName" placeholder="请输入数据通道名称"
                                            :disabled="detailDisabled" />
                                    </el-form-item>
                                </el-col>
                                
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="类别" prop="company">
                                        <el-input v-model="baseDetailForm.unit" placeholder="请输入所属公司"
                                            :disabled="detailDisabled" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="状态" prop="department">
                                        <el-input v-model="baseDetailForm.depart" placeholder="请输入所属单位"
                                            :disabled="detailDisabled" />
                                    </el-form-item>
                                </el-col>
                                
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="介绍">
                                        <el-input disabled v-model="baseDetailForm.sourceNumber"></el-input>
                                    </el-form-item>
                                </el-col>
                                
                            </el-row>

                            <el-row>
                                <el-form-item label="编号" prop="brief">
                                    <el-input v-model="baseDetailForm.brief" placeholder="请输入数据通道简介" type="textarea"
                                        maxlength="100" show-word-limit :disabled="detailDisabled" />
                                </el-form-item>
                            </el-row>

                            <el-form-item label="备注" prop="detail">
                                <el-input v-model="baseDetailForm.detail" placeholder="请输入数据通道详细介绍" type="textarea"
                                    maxlength="1000" show-word-limit :disabled="detailDisabled" />
                            </el-form-item>

                           
                        </el-form>
                    </el-form>


                </el-dialog>
            </el-col>
        </el-row>

    </div>
</template>
  
<script>

import {
    DataBaseAdd, DataBaseEdit,
    DataBaseFile, DatabaseInfoById,
    DataBaseInfoList,
    DataBaseTypeList, FileUpload,
    RuleList,
    RulesList
} from '@/api/qysj/app/DataBaseInfo'
import boxLayout from 'echarts/src/model/mixin/boxLayout'
import { buildCartesianSingleLabelElOption } from 'echarts/lib/component/axisPointer/viewHelper'
import axios from 'axios'
import fileUpload from '@/components/FileUpload/index.vue'
import { Form } from 'element-ui'

let id = 1000;

export default {
    name: "message",
    data() {

        // const data = [{id: 1,label: "关键字:",},];
        return {
            flowId: null,
            row: {},
            flowNodesData: [],
            // dialogProcessNodesVisible: false,
            dialogProcessNodesVisible: false,
            userOptions: [],
            formNodesOperate: 0,
            formData: {
                status: 0,
                type: '',
                name: '',
                desc: '',
                no: '',
                remark: '',
            },
            formNodesData: {
                type: 1,
                number: 2,
                name: '',
                desc: '',
                no: '',
                remark: '',
                nodeType: 2,
            },
            flowNodesData: [{
                type: 1,
                number: 2,
                name: '',
                desc: '',
                no: '',
                remark: '',
                nodeType: 2
            }],
            logList: [{
                data: '2024-01-15 16:01:29',
                name: 'ExaFileChunks',
                title:'测试isAll',
                content:'测试isAll'



            }],
            shangchuanshow: false,
            jieshoushow: false,

            tableData: [{
                id: 1,
                name: '李四',
                send: '张三',
                reserve: '王小虎',
                safe: '公开'
            }, {
                id: 2,
                name: '李四',
                send: '张小',
                reserve: '王小虎',
                safe: '加密'
            }, {
                id: 3,
                name: '李四',
                send: '张小',
                reserve: '王二虎',
                safe: '加密',
                children: [{
                    id: 31,
                    name: '李四',
                    send: '张小',
                    reserve: '王二虎',
                    safe: '加密',
                }, {
                    id: 32,
                    name: '李四',
                    send: '张小',
                    reserve: '王二虎',
                    safe: '加密',
                }]
            }, {
                id: 4,
                name: '李四',
                send: '张小',
                reserve: '王二虎',
                safe: '加密',
            }],

            // 查询数据通道参数
            queryParams: {
                keyword: '',
                status: 0,
                pageSize: 10,
                currPage: 1
            },
            //显示搜索表单
            showSearch: true,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 注册/修改数据通道对话框
            UpdateOpen: false,
            UpdateTitle: '',

            // 查看详情对话框
            DetailOpen: false,
            DetailTitle: '',
            // 加载表格
            // loading:true,
            // 数据通道列表
            DataBaseList: [],
            // 数据通道详情表单
            baseDetailForm: [],
            // 数据通道表单和校验规则
            baseAddForm: {},
            rules: {
                unit: [
                    { required: true, message: "所属公司不能为空", trigger: "blur" },
                ],
                resourceName: [
                    { required: true, message: "资源名称不能为空", trigger: "blur" },
                ],
                brief: [{ required: true, message: "简介不能为空", trigger: "blur" }],
                detail: [
                    { required: true, message: "详细介绍不能为空", trigger: "blur" },
                ],
            },
            activeControlName: 'defaultControl',
            activeRulesName: '1',
            activeRuleName: '1',
            // 数据通道类型列表
            dataBaseTypeList: [],
            // 选中的数据类型
            dataBaseType: [],
            // 选中的规则集
            selectedRules: '',
            // 规则集列表
            rulesList: [],
            // 规则列表
            ruleList: [],
            // 注册方式
            radio: 1,
            disabled: false,
            // 数据通道注册表单验证
            baseAddRules:
            {
                resourceName: [
                    { required: true, message: '请输入数据通道名称', trigger: 'blur' }
                ],
                brief: [
                    { required: true, message: '请输入简介', trigger: 'blur' }
                ],
                detail: [
                    { required: true, message: '请输入详情', trigger: 'blur' }
                ],
                unit: [
                    { required: true, message: '请输入所属公司', trigger: 'blur' }
                ]
            },
            // 需要返回的数据通道注册数据
            // baseAddData:{},
            selectedIconFile: null, // 当前选中的图标文件
            detailDisabled: true,//查看详情表单禁用
            // 请求数据通道类型参数
            dataBaseTypeQuery: {
                dictType: 'database_type'
            },
            // 数据通道总数
            baseTotal: 0,
            // 多选框选中的id
            selIds: []
        }
    },
    created() {
        this.getList();
        this.getDataBaseTypeList();
    },

    watch: {
        // 监听规则集变化
        selectedRules(newSelectedRules, oldSelectedRules) {
            console.log('选中的规则发生变化：', newSelectedRules);
            this.baseAddForm.rulesName = newSelectedRules;

            // 请求后端 根据规则集请求对应规则 展示

        },

    },
    methods: {
        closeProcessNodesDialog() {
            dialogProcessNodesVisible = false;
            getTableData()
        },
        enterNodesDialog() {
            this.$refs.elNodesFormRef.validate(async (valid) => {
                if (!valid) return;
                let res;
                switch (this.formNodesOperate) {
                    case 1: // 新增
                        this.formNodesData.flowId = this.flowId;
                        res = await createFlowNode(this.formNodesData);
                        break;
                    case 2: // 修改
                        res = await updateFlowNode(this.formNodesData);
                        break;
                    default: // 删除
                        res = await deleteFlowNode(this.formNodesData);
                        break;
                }
                if (res && res.code === 0) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    });
                }
                this.changeFormNodesData(4, this.formData);
                this.closeProcessNodesDialog();
            });
        },
        // 选择流程节点操作
        changeFormNodesData(type, item) {
            this.formNodesOperate = type;
            if (type === 1) { // 新增
                let objArr = [{ type: 1, IsEdit: true, name: '审核', desc: '', no: '', remark: '', nodeType: 2, number: item.number + 1 }];
                this.formNodesData = objArr[0];
                let newArr = [];
                this.flowNodesData.forEach((val, index) => {
                    if (val.id === item.id) {
                        newArr = [...this.flowNodesData.slice(0, index + 1), ...objArr, ...this.flowNodesData.slice(index + 1)];
                    }
                });
                this.flowNodesData = newArr;
            } else if (type === 2) { // 修改
                this.formNodesData = item;
                this.flowNodesData.forEach((val, index) => {
                    if (val.id === item.id) {
                        val.IsEdit = true;
                    } else {
                        val.IsEdit = false;
                    }
                });
            } else if (type === 3) { // 删除
                this.formNodesData = item;
                this.enterNodesDialog();
            } else if (type === 4) { // 保存
                this.flowNodesData.forEach((val) => {
                    val.IsEdit = false;
                });
            }
        },
        load(tree, treeNode, resolve) {
            setTimeout(() => {
                resolve([

                ])
            }, 1000)
        },
        // 表单重置
        // 表单重置
        reset() {
            (this.dataStructId = ""),
                (this.datasourceContentList = [{ name: null, tableName: null, dataType: null, remark: null, sourceId: null, },]),
                (this.baseAddForm = {
                    userId: null, brief: null, iconUrl: null,
                    datasourceDefaultControlList: [
                        { userId: null, userType: null, userLevel: null, sharedType: null, isVisible: null, remark: null, sourceId: null, dataEnsureRightType: null, dataFreedomType: null, },
                    ],
                    datasourceDefaultPriceList: [
                        { userId: null, userType: null, userLevel: null, billingType: null, usePeriod: null, productUnit: null, price: null, remark: null, },
                    ],
                    datasourceInterface: {
                        sourceTypes: null, sourceCategory: null, isAgent: null, databaseAlias: null, databaseName: null, userName: null, password: null, ipaddress: null, port: null,
                        contentType: null, engineSerial: null, header: null, method: null, system: null, version: null, url: null, authCode: null, engineId: null,
                    },
                    detail: null,
                    inputUserId: null,
                    keyword: null,
                    ownUserId: null,
                    status: null,
                    unit: null,
                    defaultPwd: null,
                    pwdSaveType: null,
                    pwdType: null,
                    datasourceContentList: [{ name: null, tableName: null, dataType: null, remark: null, sourceId: null, },],
                    datasourceStructList: [{ classAlias: null, representation: null, remark: null, datasourceContentList: [], },],
                    typeIdList: [],
                });
            this.resetForm("form");
        },
        getRulesList() {
            RulesList().then(res => {
                this.rulesList = res.data;
            })
        },
        // 获取数据类型列表
        getDataBaseTypeList() {
            DataBaseTypeList(this.dataBaseTypeQuery).then(res => {
                this.dataBaseTypeList = res.data;
            })
        },
        getList() {
            this.loading = true;
            DataBaseInfoList(this.queryParams).then(res => {
                this.DataBaseList = res.rows;
                this.baseTotal = res.total;
                this.loading = false;
            })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");//全局方法
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd(data) {
            // this.reset();
            this.UpdateOpen = true;
            console.log(data);
            this.title = "注册数据通道基本信息";
            this.shangchuanshow = data.id % 2 === 0;
            this.jieshoushow = !this.shangchuanshow;
            // this.getRulesList()
        },
        // 修改按钮操作
        handleUpdate(data) {
            const id = data.id || this.selIds;
            DatabaseInfoById(id).then(res => {
                if (res.code === 200) {
                    this.baseAddForm = res.data;
                    if (this.baseAddForm.dataBaseType && this.baseAddForm.dataBaseType.length > 0) {
                        this.dataBaseType = this.baseAddForm.databaseType.split(',')
                    }

                    this.UpdateTitle = "修改数据通道信息"
                    this.UpdateOpen = true;
                } else {
                    this.$message('获取数据通道信息失败')
                }
            })

        },
        showFlowNodesFunc(row) {
            console.log(row);
            // this.flowId = row.id;

            // row.Nodes.forEach((val, index) => {
            //   this.$set(val, 'IsEdit', false);
            // });

            // this.flowNodesData = row.Nodes || [];
            this.dialogProcessNodesVisible = true;
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/log/export', {
                ...this.queryParams
            }, `log_${new Date().getTime()}.xlsx`)
        },

        //TODO 删除数据通道（单个或多个）
        // 删除按钮操作
        handleDelete() {

        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            // console.log('selection', selection)
            this.selIds = selection.map((item) => item.id);
            // console.log('selItems', this.selItems)
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        // 查看数据通道详情
        handleDetail(data) {
            this.baseDetailForm = data;
            console.log('data', data)
            if (this.baseDetailForm.dataBaseType && this.baseDetailForm.dataBaseType.length > 0) {
                this.dataBaseType = this.baseDetailForm.databaseType.split(',')
            }
            this.DetailOpen = true;
            this.DetailTitle = '查看数据通道详情';
        },
        //TODO 测试数据通道
        // 测试数据通道
        handleCheck() {
            console.log('测试数据通道')
        },
        //TODO 上架下架数据通道
        handleUp() {
            console.log('上架')
        },
        // 注册/修改数据通道对话框涉及的事件
        handleControlTab(tab) {
            console.log('tab', tab)
        },
        // 提交按钮
        submitForm() {
            const baseAddFormInstance = this.$refs.baseAddForm;
            // 进行表单验证
            baseAddFormInstance.validate(valid => {

                if (valid && this.dataBaseType.length > 0) {
                    this.baseAddForm.databaseType = this.dataBaseType.join(',');
                    // const baseAddData = new FormData();
                    // for (const key in this.baseAddForm) {
                    //     baseAddData.append(key, this.baseAddForm[key]);
                    // }
                    if (this.baseAddForm.id) {
                        DataBaseEdit(JSON.stringify(this.baseAddForm)).then(res => {
                            if (res.code === 200) {
                                this.$message('修改成功')
                                this.UpdateOpen = false;
                                this.baseAddForm = {}
                            }
                        })
                    } else {
                        // 新增数据通道
                        DataBaseAdd(JSON.stringify(this.baseAddForm)).then(res => {
                            if (res.code === 200) {
                                this.$message('注册成功！')
                                this.UpdateOpen = false;
                                this.baseAddForm = {}
                            } else {
                                this.$message(res.data.msg)
                            }
                        })
                    }
                } else {
                    if (this.dataBaseType.length === 0) {
                        this.$message('请至少选择1个数据通道类型')
                    }
                }
            })
        },
        // icon上传
        handleIconUpload(file) {
            const form = new FormData()
            form.append('file', file);
            FileUpload(form).then(res => {
                if (res.code === 200) {
                    this.baseAddForm.iconUrl = res.url;
                }
            })
            this.selectedIconFile = file
            return false;
        },

        // 取消按钮
        cancel() {
            this.baseAddForm = {}
            this.UpdateOpen = false;
        },
        // 文件上传注册
        handleFileUpload(file) {
            console.log('event,file', file)
            const BaseFile = new FormData()
            BaseFile.append('file', file);
            DataBaseFile(BaseFile).then(res => {
                if (res.data.code === 200) {
                    this.$message('注册成功！')
                    this.UpdateOpen = false;

                } else {
                    this.$message(res.data.msg)
                }
            })
        },
        async getUserData(query) {
            try {
                const table = await this.getUserList({
                    page: 1,
                    pageSize: 100,
                    keyword: query,
                });
                if (table.code === 0) {
                    this.userOptions = table.data.list;
                }
            } catch (error) {
                // Handle errors appropriately
                console.error('Error fetching user data:', error);
            }
        },
        async getUserList(params) {

        },
    }
};
</script>
<style>.el-row {
    margin-bottom: 10px;
}</style>
  